package com.lill.org.service.impl;

import com.lill.common.component.util.IdUtil;
import com.lill.org.dao.ICompanyArchitectureDao;
import com.lill.org.dao.ICompanyBranchDao;
import com.lill.org.dao.IDepartmentDao;
import com.lill.org.dao.IEmployeeDao;
import com.lill.org.model.CompanyArchitectureModel;
import com.lill.org.service.ICompanyArchitectureService;
import com.lill.org.service.IEmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公司架构Service实现类
 *
 * @author lill
 * @date 2019-04-24 15:25:17
 */
@Service("com.lill.org.service.impl.CompanyArchitectureServiceImpl")
public class CompanyArchitectureServiceImpl implements ICompanyArchitectureService {
    @Autowired
    private ICompanyArchitectureDao companyArchitectureDao;
    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentDao departmentDao;
    @Autowired
    private ICompanyBranchDao branchDao;

    public CompanyArchitectureModel queryObject(String id) {
        return companyArchitectureDao.queryObject(id);
    }

    @Override
    public List<CompanyArchitectureModel> queryByForList(Map<String, Object> map,String branchId) {
    	List<CompanyArchitectureModel> objects = new ArrayList<>();  
        List<CompanyArchitectureModel> list = companyArchitectureDao.queryList(map);
        if(StringUtils.isNotEmpty(branchId)&&list!=null&& list.size()>0){
        	for (CompanyArchitectureModel companyArchitectureModel : list) {
        		if(companyArchitectureModel.getParentId()!=null&&companyArchitectureModel.getParentId().equals("0")){
        			objects.add(companyArchitectureModel);
        		}
        		
        		if(companyArchitectureModel.getId()!=null&&companyArchitectureModel.getId().equals(branchId)){
        			objects.add(companyArchitectureModel);
        			
        			for (CompanyArchitectureModel architectureModel : list) {
        				if(companyArchitectureModel.getParentId()!=null&&architectureModel.getId()!=null
        						&&companyArchitectureModel.getParentId().equals(architectureModel.getId())){
        					objects.add(architectureModel);
        				}
        				if(architectureModel.getParentId()!=null&&companyArchitectureModel.getId().equals(architectureModel.getParentId())){
        					objects.add(architectureModel);
        				}
        			}
        		}
        	}
            return objects;
        }
        return list;

    }

    public List<CompanyArchitectureModel> queryList(Map<String, Object> map) {
        return companyArchitectureDao.queryList(map);
    }

    @Override
    public List<CompanyArchitectureModel> queryCompanyAll(Map<String, Object> map) {


        return companyArchitectureDao.queryCompanyAll(map);
    }

    public List<CompanyArchitectureModel> customerQueryAll(Map<String, Object> map) {
        return companyArchitectureDao.customerQueryAll(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return companyArchitectureDao.queryTotal(map);
    }

    public int save(CompanyArchitectureModel orgCompanyArchitecture) {
        orgCompanyArchitecture.setId(IdUtil.createIdbyUUID());
        return companyArchitectureDao.save(orgCompanyArchitecture);
    }

    public int update(CompanyArchitectureModel orgCompanyArchitecture) {
        return companyArchitectureDao.update(orgCompanyArchitecture);
    }

    public int delete(String id) {
        return companyArchitectureDao.delete(id);
    }

    public int deleteBatch(String[] ids) {
        return companyArchitectureDao.deleteBatch(ids);
    }
    
	public int deleteLogicByMap(Map<String, Object> map) {
		boolean result=true;
		if(null!=map&&map.size()>0&&map.containsKey("ids")&&null!=map.get("ids")){
			String[] idList=(String[]) map.get("ids");
			for (int i = 0; i < idList.length; i++) {
				map.put("parentId", idList[i]);
				int num=companyArchitectureDao.queryTotal(map);
				if(num>0){
					result=false;break;
				}
			}
			if(result){
				for (int i = 0; i < idList.length; i++) {
					map.put("departId", idList[i]);
					int num=employeeDao.queryTotal(map);
					if(num>0){
						result=false;break;
					}
				}
			}
		}
		if(result){
			int num=departmentDao.deleteLogicByMap(map);
			num+=employeeService.deleteLogicByMap(map);
			num+=branchDao.deleteLogicByMap(map);
			
			return num;
		}else{
			return 0;
		}
	}

    @Override
    public List<CompanyArchitectureModel> querySaleUser(Map<String, Object> map) {
        return companyArchitectureDao.querySaleUser(map);
    }

    @Override
    public List<CompanyArchitectureModel> querySaleUser2(Map<String, Object> map) {
        return companyArchitectureDao.querySaleUser2(map);
    }
    public int updatePersonNum(Map<String, Object> mapParam){
        return companyArchitectureDao.updatePersonNum(mapParam);
    }
    
    public void updateTreePersonNum(String departId,int num){
    	if(StringUtils.isNotEmpty(departId)&&0!=num){
    		CompanyArchitectureModel architecture=companyArchitectureDao.queryObject(departId);
    		Map<String, Object> mapParam=new HashMap<String, Object>();
    		mapParam.put("ids", (architecture.getParentList()+","+architecture.getId()).split(","));
    		mapParam.put("num", num);
    		companyArchitectureDao.updatePersonNum(mapParam);
    	}
    }

    @Override
    public List<Map<String, Object>> findBranchList(Map<String, Object> param,Boolean flag) {
        List<String> strings = companyArchitectureDao.queryCompanyIdByBigScreen(param);
        List<Map<String, Object>> result=new ArrayList<>();
        List<CompanyArchitectureModel> list=new ArrayList<>();
        List<CompanyArchitectureModel> branch=new ArrayList<>();
        StringBuilder branchIds=new StringBuilder();
        Map<String,List<CompanyArchitectureModel>> branchDepart=new HashMap<>();
        Integer _4s=0;
        Integer _1s=0;
        Integer _service=0;
        Integer _vmShop=0;
        Integer _twoInternet=0;
        if (strings!=null && strings.size()>0){
            for (String s:strings){
                Map<String,Object> p=new HashMap<>();
                p.put("parentList",s);
                List<CompanyArchitectureModel> model = companyArchitectureDao.queryList(p);
                if (model!=null && model.size()>0){
                    for (CompanyArchitectureModel m:model){
                        if (m.getType().equals("C")){
                            branch.add(m);
                            if (!StringUtils.isEmpty(m.getBranchId())) {
                                branchIds.append(m.getBranchId());
                                branchIds.append(",");
                            }
                        }
                        if (m.getType().equals("D")){
                            list.add(m);
                        }
                    }
                }
            }
            if (list.size()>0 && branch.size()>0){
                for (CompanyArchitectureModel b:branch){
                    List<CompanyArchitectureModel> items=new ArrayList<>();
                    for (CompanyArchitectureModel c:list){
                        if (c.getParentId().equals(b.getId())){
                            items.add(c);
                        }
                    }
                    branchDepart.put(b.getId(),items);
                }
            }
            if (!branchDepart.isEmpty()){
                for (String s:branchDepart.keySet()){
                    int itemRRecord=0;
                    int front=0;
                    int after=0;
                    List<CompanyArchitectureModel> items = branchDepart.get(s);
                    if (!items.isEmpty()){
                        StringBuilder sb=new StringBuilder();
                        for (CompanyArchitectureModel i:items){
                            sb.append(i.getName());
                            sb.append(",");
                        }
                        if (sb.toString().contains("销售")){
                            itemRRecord+=1;
                            front=1;
                        }
                        if (sb.toString().contains("售后")){
                            itemRRecord+=1;
                            after=1;
                        }
                        if (itemRRecord==0){
                            _vmShop++;
                        }
                        if (itemRRecord==1){
                            if (after==1){
                                _service++;
                            }
                            if (front==1){
                                _1s++;
                            }
                        }
                        if (itemRRecord==2){
                            _4s++;
                        }

                    }else {
                        _service++;
                    }
                }
            }
        }
        if (!flag) {
            param.put("businessStatus",1);
             _twoInternet=companyArchitectureDao.queryTwoInternet(param);
            param.put("businessStatus",0);
             _vmShop=companyArchitectureDao.checkBranchData(param);
             _4s=_4s-_vmShop;
            String[] names = {"4S店(营业中)","4S店(歇业中)", "1S店", "二级站点", "服务站点"};
            Integer[] sums = {_4s, _vmShop,_1s,_twoInternet,_service};
            for (int i = 0; i < names.length; i++) {
                Map<String, Object> item = new HashMap<>();
                item.put("branchName", names[i]);
                item.put("branchNum", sums[i]);
                result.add(item);
            }
        }
        else {
            String ids = branchIds.substring(0, branchIds.length() - 1);
            Map<String,Object> par=new HashMap<>();
            par.put("ids",ids);
            List<Map<String, Object>> maps = companyArchitectureDao.queryBranchByBigScreen(par);
            if (!maps.isEmpty()){
                Map<String, List<Map<String, Object>>> pid = maps.stream().collect(Collectors.groupingBy(e -> {
                    return (String) e.get("pid");
                }));
                for (String k:pid.keySet()){
                    int total=0;
                    Map<String,Object> items=new HashMap<>();
                    List<Map<String, Object>> item = pid.get(k);
                    if (item!=null){
                        items.put("name",item.get(0).get("name"));
                        items.put("id",k);
                        total=item.size();
//                        for (Map<String, Object> m:item){
//                            total++;
//                        }
                        items.put("num",total);
                    }
                    result.add(items);
                }

            }
        }
        return result;
    }

    @Override
    public List<CompanyArchitectureModel> queryEmployeeUser(Map<String, Object> params) {
        return companyArchitectureDao.queryEmployeeUser(params);
    }

    @Override
    public List<CompanyArchitectureModel> customerQueryAllUpdate(Map<String, Object> map) {
        return companyArchitectureDao.customerQueryAllUpdate(map);
    }

}
